package org.lq.ht.util;
/**
 * 	数据库连接工具类
 * @author 杨培林
 * @phone 13603738558
 * 
 * @package org.lq.sm.util
*/

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class JDBCUtil {


	private static final String USER = "root";
	private static final String PASSWORD = "root";
	private static final String DRIVER =  "com.mysql.jdbc.Driver";
	private static final String URL = "jdbc:mysql://localhost:3306/hotel";

	static {
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public static Connection getConn() {
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(URL, USER, PASSWORD);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	/**
	 * 	通用的添加删除修改方法
	 * @param sql  需要执行的SQL语句
	 * @param param 设置传递给SQL语句中的赋值参数
	 * @return 返回受影响函数 >0 : 成功  否则  <=0 失败
	 * @throws SQLException
	 */
	public static int executeUpdate(String sql,Object...param) throws SQLException {
		int num = 0;
		try(
				Connection conn = getConn();
				PreparedStatement ps = conn.prepareStatement(sql);
				){
			if(param!=null && param.length>0) {
				for (int i = 0; i < param.length; i++) {
					//给?号赋值从1开始
					ps.setObject(i+1, param[i]);
				}
			} 
			num = ps.executeUpdate();
		}catch (SQLException e) {
			throw e;
		}
		return num;
	}

	/**
	 * 	通用查询方法
	 * @param <T> 需要返回的实例对象(泛型中的类型)
	 * @param sql 需要执行的查询SQL语句
	 * @param in	对实例对象创建的结构
	 * @param params	传递的参数
	 * @return	返回结果,list.size()>0代表查询成功
	 * @throws SQLException
	 */
	public static <T> List<T> executeQuery(String sql,Instantiation<T> in,Object...params) throws SQLException{
		List<T> list = new ArrayList<T>();
		ResultSet rs = null;
		try(
				Connection conn = getConn();
				PreparedStatement ps = conn.prepareStatement(sql);
				){
			if(params!=null && params.length>0) {
				for (int i = 0; i < params.length; i++) {
					ps.setObject(i+1, params[i]);
				}
			}
			 rs = ps.executeQuery();
			 while(rs.next()) {
				 list.add(in.instance(rs));
			 }
			
		}catch (SQLException e) {
			throw e;
		}finally {
			if(rs!=null) {
				rs.close();
			}
		}
		return list;
	}

	public static void closeAll(ResultSet rs,PreparedStatement ps,Connection conn) {
		try {
			if(rs != null) {
				rs.close();
				rs = null;
			}
			if(ps != null) {
				ps.close();
				ps = null;
			}
			if(conn!=null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}

